<?php

namespace app\model;

use think\Model;
use think\facade\Env;
use app\model\Enter;
use app\model\WorkHour;
use app\model\Staff;
use app\model\OnJob;

class User extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 登录
     *
     * @param [type] $login_data
     * @return void
     */
    public static function login($login_data)
    {
        if ($login_data['type'] == 1) {
            // $user = self::where('mobile', $login_data['mobile'])->where('delete_time', null)->find();
            $user = self::where('openid', $login_data['openid'])->where('delete_time', null)->find();
            if (empty($user)) {
                $user = self::create([
                    // 'mobile' => $login_data['mobile'],
                    'openid' => $login_data['openid'],
                    'attr'   => $login_data['attr']
                ]);
            }
            // else {
            //     $user->openid = $login_data['openid'];
            //     $user->save();
            // }
        } elseif ($login_data['type'] == 2) {
            $user = self::where('mobile', $login_data['mobile'])->where('delete_time', null)->find();
            if (empty($user)) {
                error('用户未注册');
            }
            if ($user['password'] != encryption($login_data['password'])) {
                error('密码错误');
            }
        } elseif ($login_data['type'] == 3) {
            $user = self::where('mobile', $login_data['mobile'])->where('delete_time', null)->find();
            if (empty($user)) {
                error('用户未注册');
            }
        } else {
            error('参数错误');
        }

        try {
            $user->last_login_time = date('Y-m-d H:i:s');
            $user->save();
            $user['type'] = Enter::where('user_id', $user['id'])->value('type') ?? 5;
            $user['cause'] = Enter::where('user_id', $user['id'])->value('cause') ?? '';
        } catch (\Exception $e) {
            error($e->getMessage());
        }
        return $user;
    }

    /**
     * 注册
     *
     * @param [type] $register_date 注册数据
     * @return void
     */
    public static function register($register_data)
    {
        self::startTrans();
        try {
            $user = self::where('mobile', $register_data['mobile'])->where('delete_time', null)->find();
            if (!empty($user)) {
                if ($user['status'] == 1) {
                    error('此账号已被锁定');
                }
                error('此手机号已经注册');
                // if (!empty($user['openid']) && empty($user['password'])) {
                //     self::where('id', $user['id'])->update(['password' => encryption($register_data['password'])]);
                // }
            } else {
                self::create([
                    'mobile'   => $register_data['mobile'],
                    'password' => encryption($register_data['password']),
                ]);
            }
            self::commit();
        } catch (\Exception $e) {
            self::rollback();
            error('数据库内部错误');
        }

        return true;
    }

    /**
     * 忘记密码
     *
     * @param [type] $forget_password_data 忘记密码数据
     * @return void
     */
    public static function forgetPassword($forget_password_data)
    {
        try {
            self::where('mobile', $forget_password_data['mobile'])->update(['password' => encryption($forget_password_data['password'])]);
        } catch (\Exception $e) {
            error('数据库内部错误');
        }

        return true;
    }

    /**
     * 获取用户信息
     *
     * @param [type] $user_id 用户id
     * @return void
     */
    public static function getUserInfo($user_id)
    {
        $user = self::alias('u')
            ->join('enter e', 'u.id = e.user_id')
            ->field('u.id, u.attr, e.name, e.num, e.phone, e.shenfen, e.enter_sheng, e.enter_shi, e.enter_xian, e.enter_address_details, e.boss_id')
            ->where('u.id', $user_id)
            ->find();
        if (!empty($user)) {
            if (!empty($user['boss_id'])) {
                $boss_info = Enter::where('user_id', $user['boss_id'])->field('name, shenfen')->find();
                $user['boss_name'] = $boss_info['name'];
                $user['boss_shenfen'] = $boss_info['shenfen'];
            } else {
                $user['boss_name'] = '';
                $user['boss_shenfen'] = '';
            }
            // 待结算金额
            $num = Enter::where('user_id', $user_id)->value('num');
            $user['wait_payment_money'] = WaitPayment::where('enter_num', $num)->sum('money') ?? 0;

            // 入职、离职、待入职员工数
            $staff_id = Staff::where('boss_id', $user_id)->column('id');
            $staff_id_num = Staff::where('boss_id', $user_id)->column('id_num');
            $user['work_hour'] = WorkHour::where('id_num', 'in', $staff_id_num)->sum('work_hour');
            $user['on_job'] = OnJob::where('staff_id', 'in', $staff_id)->where('type', 1)->count();
            $user['leave_job'] = OnJob::where('staff_id', 'in', $staff_id)->where('type', 3)->count();
            $on_job_staff_id = OnJob::where('staff_id', 'in', $staff_id)->where('type', 1)->column('staff_id');
            $user['wait_job'] = Staff::where('boss_id', $user_id)->whereNotIn('id', $on_job_staff_id)->count();

            // 待办事项数
            $user['to_do'] = Enter::toDo($user_id)['count'];
            return $user;
        } else {
            error('没有此用户');
        }
    }

    /**
     * 修改用户信息
     *
     * @param [type] $user_id 用户id
     * @param [type] $update_user_info_data 用户修改信息
     * @return void
     */
    public static function updateUserInfo($user_id, $update_user_info_data)
    {
        try {
            self::where('id', $user_id)->update($update_user_info_data);
            return true;
        } catch (\Exception $e) {
            error('数据库内部错误');
        }
    }

    /**
     * 用户修改密码
     *
     * @param [type] $user_id 用户id
     * @param [type] $update_password_date 用户修改密码数据
     * @return void
     */
    public static function updateUserPassword($user_id, array $update_password_data)
    {
        $password = self::where('id', $user_id)->value('password');
        if (encryption($update_password_data['old_password']) !== $password) {
            error('原密码错误');
        }
        if (encryption($update_password_data['new_password']) == $password) {
            error('新密码不能和原密码相同');
        }

        try {
            self::where('id', $user_id)->update(['password' => encryption($update_password_data['new_password'])]);
            return true;
        } catch (\Exception $e) {
            error('数据库内部错误');
        }
    }

    /**
     * 头像获取器
     *
     * @param [type] $value
     * @param [type] $data
     * @return void
     */
    public function getAttrAttr($value, $data)
    {
        if (empty($value)) {
            return '';
        }
        if (strpos($value, 'http') == false) {
            $value = Env::get('APP.PATH') . $value;
        }
        return $value;
    }

    /**
     * 族群
     *
     * @param [type] $user_id
     * @return void
     */
    public static function getGroup($user_id)
    {
        $id = Enter::where('user_id', $user_id)->value('id');
        $Enter_info = Enter::getInfo($id);
        $group = [
            'name'        => $Enter_info['name'],
            'shenfen'     => $Enter_info['shenfen'],
            'enter_sheng' => $Enter_info['enter_sheng'],
            'enter_shi'   => $Enter_info['enter_shi'],
            'enter_xian'  => $Enter_info['enter_xian'],
            'enter_xiang' => $Enter_info['enter_xiang'],
            'yizhan'      => $Enter_info['yizhan'],
        ];
        return $group;
    } 

    /**
     * 待结算金额
     *
     * @param [type] $user_id
     * @return void
     */
    public static function waitPaymenMoney($user_id)
    {
        $time = input('time');
        if (empty($time)) {
            $time = strtotime(date('Y-m-1', time()));
        } else {
            $time = strtotime(date('Y-m-1', strtotime($time)));
        }

        $yizhan = self::getGroup($user_id)['yizhan'];
        foreach ($yizhan as $k => $v) {
            if (!empty($v['child'])) {
                foreach ($v['child'] as $kk => $vv) {
                    if (!empty($vv['child'])) {
                        foreach ($vv['child'] as $kkk => $vvv) {
                            $num = Enter::where('enter_xiang', $vvv)->value('num');
                            $money = WaitPayment::where('enter_num', $num)->where('time', $time)->value('money') ?? 0;
                            $yizhan[$k]['child'][$kk]['child'][$kkk] = [$vvv, $money];
                        }
                    }
                }
            }
        }

        $y_start = strtotime(date('Y-1-1', time()));
        $y_end = strtotime(date('Y-12-31', time()));

        $info = Enter::field('num, shenfen, enter_sheng, enter_shi, enter_xian, enter_xiang')->where('user_id', $user_id)->find();
        $all = WaitPayment::where('enter_num', $info['num'])->whereBetween('time', "{$y_start}, {$y_end}")->sum('money');
        return ['all' => $all, 'info' => $info, 'yizhan' => $yizhan];
    }
}
